package com.huafeng.commonutil;

import com.huafeng.model.entity.SysMenu;
import com.huafeng.model.vo.MetaVo;
import com.huafeng.model.vo.RouterVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;

import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author 花风
 * @date 2023/8/17 19:56
 * @Description 路由工具类
 */
public class RouterHelper {
    private RouterHelper(){
    }

    public static List<RouterVo> buildRouters(List<SysMenu> sysMenuList){
        List<RouterVo> routerVoList = new LinkedList<>();
        sysMenuList.forEach(sysMenu -> {
            RouterVo routerVo = new RouterVo();
            routerVo.setHidden(false);
            routerVo.setAlwaysShow(false);
            routerVo.setPath(getRouterPath(sysMenu));
            routerVo.setComponent(sysMenu.getComponent());
            routerVo.setMeta(new MetaVo(sysMenu.getName(),sysMenu.getIcon()));
            List<SysMenu> children = sysMenu.getChildren();
            // 如果当前是菜单，需将按钮去对应的路由加载出来，如："角色授权"按钮对应的路由在"系统管理"下面
            if (sysMenu.getType() == 1){
                if (!CollectionUtils.isEmpty(children)){
                    List<SysMenu> hiddenMenuList = children.stream().filter(menu -> {
                        return !StringUtils.isEmpty(menu.getComponent());
                    }).collect(Collectors.toList());
                    hiddenMenuList.forEach(hiddenMenu -> {
                        RouterVo hiddenRouter = new RouterVo();
                        hiddenRouter.setHidden(true);
                        hiddenRouter.setAlwaysShow(false);
                        hiddenRouter.setPath(getRouterPath(hiddenMenu));
                        hiddenRouter.setComponent(hiddenMenu.getComponent());
                        hiddenRouter.setMeta(new MetaVo(hiddenMenu.getName(),hiddenMenu.getIcon()));
                        routerVoList.add(hiddenRouter);
                    });
                }
            }else {
                if (!CollectionUtils.isEmpty(children)){
                    routerVo.setAlwaysShow(true);
                    routerVo.setChildren(buildRouters(children));
                }
            }
            routerVoList.add(routerVo);
        });
        return routerVoList;
    }

    private static String getRouterPath(SysMenu sysMenu){
        String routerPath = "/" + sysMenu.getPath();
        if (sysMenu.getParentId() != 0){
            routerPath = sysMenu.getPath();
        }
        return routerPath;
    }

}
